// app/src/main/java/com/example/hlddz2/repository/ProductRepository.java
package com.example.hlddz2.repository;

import android.util.Log;

import com.example.hlddz2.model.NavItemResponse;
import com.example.hlddz2.model.Product;
import com.example.hlddz2.model.ProductListResponse;
import com.example.hlddz2.network.ApiService;
import com.example.hlddz2.model.Category;
import com.example.hlddz2.model.CategoryResponse;
import com.example.hlddz2.model.ProductDetailResponse;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class ProductRepository {
    private static final String TAG = "ProductRepository";
    private ApiService apiService;

    public ProductRepository(ApiService apiService) {
        this.apiService = apiService;
    }

    public Observable<NavItemResponse> getNavItems() {
        return apiService.getNavItems()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<List<Product>> getGoodsList(String query, int cid, int pagesize, int pagenum) { // 注意返回类型改为了 List<Product>
        return apiService.getGoodsList(query, cid, pagesize, pagenum)
                .map(response -> { // 使用 map 操作符来转换数据
                    List<Product> allProducts = new ArrayList<>();
                    if (response != null && response.getMessage() != null) {
                        for (ProductListResponse.Group group : response.getMessage()) {
                            if (group.getGoods() != null) {
                                allProducts.addAll(group.getGoods()); // 将每个组的商品添加到总列表
                            }
                        }
                    }
                    Log.d(TAG, "Extracted " + allProducts.size() + " products from API response.");
                    return allProducts; // 返回合并后的商品列表
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<List<Category>> getCategories() {
        return apiService.getCategories()
                .map(CategoryResponse::getMessage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<ProductDetailResponse.ProductDetail> getGoodsDetail(int goodsId) {
        return apiService.getGoodsDetail(goodsId)
                .map(ProductDetailResponse::getMessage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}